
package cn.westv.scps.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
 * 
 * 该类用于读取配置文件 <br/>
 * <p>Description:<br/>
 *    <p>TODO 该类用于读取配置文件
 *
 * <p>For Examples <br/>
 * <PRE>
 *      TODO 代码使用示例
 * </PRE>
 * <p>
 */
public class PropertiesUtil {
	private static PropertiesUtil instance = null;

	public static PropertiesUtil getInstance() {
		if(null == instance){
			instance = new PropertiesUtil();
		}
		return instance;
	}
	/**
	 * 
	 * @param sourceFileName 配置文件名，如果为空，则默认读取Application.properties
	 * 如果db则是db/db.properties
	 * @param key 要读取的键
	 * @return 字符串
	 */
	public String getPro(String sourceFileName,String key){
		if(null == sourceFileName || sourceFileName == "" || sourceFileName.trim().length() == 0){
			sourceFileName = "config/app.properties";
		}
		if(!sourceFileName.startsWith("/")){
			sourceFileName = "/"+sourceFileName;
		}
		InputStream f = PropertiesUtil.class.getResourceAsStream(sourceFileName);
		Properties p = new Properties();
		try {
			p.load(f);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				f.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return p.get(key)==null?null:p.get(key).toString();
	}
	
	public boolean setKeyValue(String sourceFileName,String key,String value){
		if(null == sourceFileName || sourceFileName == "" || sourceFileName.trim().length() == 0){
			sourceFileName = "config/app.properties";
		}
		if(!sourceFileName.startsWith("/")){
			sourceFileName = "/"+sourceFileName;
		}
		InputStream f = PropertiesUtil.class.getResourceAsStream(sourceFileName);
		Properties p = new Properties();
		try {
			p.load(f);
			p.setProperty(key, value);
		} catch (IOException e) {
		    e.printStackTrace();
			return false;
		}finally{
			try {
				f.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
		
	}
	public static void main(String[] args) {
		Object xx = PropertiesUtil.getInstance().getPro("", "1");
		System.out.println(xx.toString());
	}
}
